package com.wushijia.highconcurrency.threadpool;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.wushijia.highconcurrency.utils.ThreadPoolExecutorUtils;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ExceptionTaskTest {

  public static void main(String[] args) {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 0L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
        new ThreadFactoryBuilder().setNameFormat("pool-%d").setUncaughtExceptionHandler((Thread t, Throwable e) -> {
          log.error("pool happen exception, thread is {}", t, e);
        }).build());
    for (int i = 0; i < 5; i++) {
      //错误会被隐藏
      //executor.submit(new DivTask(100, i));
      //下面这两种错误会暴露
      executor.execute(new ExceptionTask(100, i));
      //或者下面这种异常会被保存到get()里，当调用get方法时，将异常抛出
      //Future future = executor.submit(new DivTask(100, i));
      //future.get();
      log.info(ThreadPoolExecutorUtils.getThreadPoolExecutorInfo("异常测试", executor));
    }

  }

  public static class ExceptionTask implements Runnable {

    int a, b;

    public ExceptionTask(int a, int b) {
      this.a = a;
      this.b = b;
    }

    @Override
    public void run() {
      try {
        double e = a / b;
        System.out.println(e);
      } catch (Exception e) {
        log.error("任务执行错误：", e);
      }

    }
  }
}
